package com.jin.webvideo.controller;

import com.jin.webvideo.base.LoginHandler;
import com.jin.webvideo.exception.DataException;
import com.jin.webvideo.entity.ResultEntity;
import com.jin.webvideo.service.UserService;
import com.jin.webvideo.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private VideoService videoService;
    @Autowired
    private UserService userService;

    /**
     * 历史页面
     * @return
     */
    @GetMapping("/history")
    public String history(){
        return "playhis#c";
    }

    /**
     * 上传用户观看的进度
     * @param session
     * @param pkey
     * @param time
     * @return
     * @throws DataException
     */
    @ResponseBody
    @PostMapping("/progress")
    public ResultEntity progress(HttpSession session, @RequestParam("url") String pkey, @RequestParam("time")long time) throws DataException {
        String account = LoginHandler.assetGetLogin(session);
        return ResultEntity.success("success" ,videoService.upsertProgress(account, pkey, time));
    }

    /**
     * 新用户注册
     * @param account 账号
     * @param password 密码
     * @param activekey 注册码
     * @return
     * @throws DataException
     */
    @PostMapping("/register")
    public String register(@RequestParam("account") String account, @RequestParam("password")String password, @RequestParam("activekey") String activekey) throws DataException {
        boolean registerSuccess = userService.register(account, password, activekey);
        if (registerSuccess){
            return "redirect:/login";
        }
        return "redirect:/register";
    }

    /**
     * 观看历史记录
     * @param session
     * @param pagesize
     * @param pageno
     * @return
     * @throws DataException
     */
    @ResponseBody
    @GetMapping("/videoHistory")
    public ResultEntity videoHis(HttpSession session, int pagesize, int pageno) throws DataException {
        String account = LoginHandler.assetGetLogin(session);
        List<Map<String, String>> list = videoService.listVideoHistory(account, pageno, pagesize);
        Map<String,Object> r = new HashMap<>();
        if (list.size() == pagesize + 1){
            r.put("more", true);
            r.put("list", list.subList(0, pagesize));
        }
        else{
            r.put("more", false);
            r.put("list", list);
        }
        return ResultEntity.success(r);
    }
}
